import pymongo
from .settings import MONGO_HOST, MONGO_PORT, MONGO_NAME, MONGO_COLLECTION
# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html


# useful for handling different item types with a single interface
from itemadapter import ItemAdapter


class DoubanPipeline:
    def __init__(self):
        host = MONGO_HOST
        port = MONGO_PORT
        name = MONGO_NAME
        collection = MONGO_COLLECTION
        # 连接mongodb客户端
        client = pymongo.MongoClient(host, port)
        # 选择数据库
        db = client[name]
        # 选择表 并赋值给自定义的类成员
        self.tb = db[collection]

    def process_item(self, item, spider):
        self.tb.insert(dict(item))
        return item
